// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dfa.axis.v1_19.matchtables;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Interacts with user asking to create OAuth2 Authorization using a web browser.  Class
 * then set ups OAuth2 credential for all SOAP requests. Can also use OAuth2 refresh tokens
 * to establish OAuth2 credential without user interaction.
 *
 * @author Moshe Kahan
 */
class OAuth2CommandLine {

  private static final String SCOPE = "https://www.googleapis.com/auth/dfatrafficking";

  // This callback URL will allow you to copy the token from the success screen.
  private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";

  private String clientId;
  private String clientSecret;
  private String refreshToken;

  /**
   * Constructs OAuth2 utility class that can interact via command line or use a refresh token.
   * @param clientId OAuth2 client ID for this application
   * @param clientSecret OAuth2 client secret for this application
   * @param refreshToken OAuth2 refresh token for this user
   */
  OAuth2CommandLine(String clientId, String clientSecret, String refreshToken) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.refreshToken = refreshToken;
  }

  /**
   * Use refresh token or interact with user to return OAuth2 credentials.
   * @return OAuth2 credential to be used for DFA SOAP API session
   * @throws IOException if error encountered communicating with Google authorization servers.
   */
  Credential getOAuth2Credential() throws IOException {

    // Create the OAuth2 credential.
    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(new NetHttpTransport())
        .setJsonFactory(new JacksonFactory())
        .setClientSecrets(clientId, clientSecret)
        .build();

    if (refreshToken == null) {
      // Get OAuth2 via user interaction
      GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
          new NetHttpTransport(),
          new JacksonFactory(),
          clientId,
          clientSecret,
          Lists.newArrayList(SCOPE))
          .setApprovalPrompt("force")
          // Set the access type to offline so that the token can be refreshed.
          // By default, the library will automatically refresh tokens when it
          // can, but this can be turned off by setting
          // dfa.api.refreshOAuth2Token=false in your ads.properties file.
          .setAccessType("offline").build();

      String authorizeUrl =
          authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
      System.out.println("Paste this url in your browser: \n" + authorizeUrl + '\n');

      // Wait for the authorization code.
      System.out.println("Type the code you received here: ");
      String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

      // Authorize the OAuth2 token.
      GoogleAuthorizationCodeTokenRequest tokenRequest =
          authorizationFlow.newTokenRequest(authorizationCode);
      tokenRequest.setRedirectUri(CALLBACK_URL);
      GoogleTokenResponse tokenResponse = tokenRequest.execute();

      System.out.println("Future application runs can use this OAuth2 Refresh token: "
          + tokenResponse.getRefreshToken() + " if set in the matchtables.properties file.");
      credential.setFromTokenResponse(tokenResponse);
    } else {
      credential.setRefreshToken(refreshToken);
    }

    if (credential.refreshToken()) {
      System.out.println("OAuth2 credential was refreshed successfully.");
    } else {
      System.out.println("OAuth2 credential was not refreshed successfully.");
    }

    return credential;
  }
}
